package member

import (
	"fmt"
	"time"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/db"
	"woo-server/models/db/content"
)

// 用户表
type Users struct {
	*structs.Common `gorm:"-" json:"-"`
	MemberId        uint64               `gorm:"primary_key;AUTO_INCREMENT;column:member_id;"` // 自增主键
	GradeId         uint64               `gorm:"column:grade_id;size:150;"`                    // 会员等级ID
	FileId          uint64               `gorm:"column:image_id;size:11;"`                     // 头像id
	NickName        string               `gorm:"column:nickname;size:150;"`                    // 昵称
	UserName        string               `gorm:"column:username;size:150;"`                    // 用户名
	PassWord        string               `gorm:"column:password;size:150;"`                    // 经过MD5加密的用户密码
	Mobile          string               `gorm:"column:mobile;size:50;"`                       // 手机号码
	Email           string               `gorm:"column:email;size:150;"`                       // 电子邮箱
	LastLoginIp     string               `gorm:"column:last_login_ip;size:150;"`               // 上一次登录IP地址
	BeforeLoginIp   string               `gorm:"column:before_login_ip;size:150;"`             // 本次登录IP地址
	LastLoginTime   *time.Time           `gorm:"column:last_login_time;type:update_time;"`     // 上一次登录时间
	BeforeLoginTime *time.Time           `gorm:"column:before_login_time;type:update_time;"`   // 本次登录时间
	Status          int                  `gorm:"column:status;size:150;"`                      // 用户状态 1 :正常 0:禁用
	Avatar          []content.UploadFile `gorm:"foreignKey:FileId;references:FileId"`          // 文件模型返回的用户头像数组
	Grade           GRADE                `gorm:"foreignKey:GradeId"`                           // 角色模型返回的用户角色
	db.Basics
}

// 表名
func (u *Users) TableName() string {
	return "woo_member"
}

// 初始化
func NewMember(com *structs.Common) *Users {
	d := &Users{}
	d.Common = com
	if com.Claim != nil {
		//d.CreateUser = com.Claim.Id
		//d.UpdateUser = com.Claim.Id
	}
	return d
}

func (u *Users) Column() []structs.ColumnCommon {

	result := make([]structs.ColumnCommon, 0)
	result = append(result, structs.ColumnCommon{Title: "ID", DataIndex: "MemberId"})
	result = append(result, structs.ColumnCommon{Title: "头像", DataIndex: "ImageId"})
	result = append(result, structs.ColumnCommon{Title: "昵称", DataIndex: "NickName"})
	result = append(result, structs.ColumnCommon{Title: "用户名", DataIndex: "UserName"})
	result = append(result, structs.ColumnCommon{Title: "用户角色", DataIndex: "Grade.GradeName"})
	result = append(result, structs.ColumnCommon{Title: "电子邮箱", DataIndex: "Email"})
	result = append(result, structs.ColumnCommon{Title: "上次登录IP", DataIndex: "LastLoginIp"})
	result = append(result, structs.ColumnCommon{Title: "上次登录事件", DataIndex: "LastLoginTime"})
	result = append(result, structs.ColumnCommon{Title: "状态", DataIndex: "Status"})
	result = append(result, structs.ColumnCommon{Title: "操作", DataIndex: "Operation"})
	return result
}

func (u *Users) Forms() []structs.FormsCommon {
	result := make([]structs.FormsCommon, 0)
	gModel := NewGrade(u.Common)
	options, _ := gModel.GetListAndTotal("", 1, 1000)

	result = append(result, structs.FormsCommon{Key: "MemberId", Label: "主键ID", Type: "hidden", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "NickName", Label: "昵称", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "UserName", Label: "用户名", Type: "hidden", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "GradeId", Label: "用户角色", Type: "OnceSelect", Options: gModel.SetOption(options)})
	result = append(result, structs.FormsCommon{Key: "ImageId", Label: "头像", Type: "onlyUploadImage", Options: "Avatar"})
	//result = append(result, structs.FormsCommon{Key: "PassWord", Label: "密码", Type: "hidden", Options: ""})
	result = append(result, structs.FormsCommon{Key: "Email", Label: "电子邮箱", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "LastLoginIp", Label: "上次登录IP", Type: "hidden", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "LastLoginTime", Label: "上次登录时间", Type: "hidden", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "Status", Label: "状态", Type: "switch", Options: []string{}})
	return result
}

// 创建
func (u *Users) Create() error {
	return utils.GORM.Debug().Table(u.TableName()).Create(u).Error
}

// 批量创建
func (u *Users) BatchCreate(data []*Users) error {
	return utils.GORM.Debug().Table(u.TableName()).Create(data).Error
}

// 获取分页列表及总数
func (u *Users) GetUserListAndTotal(search string, page int, pageSize int) ([]*Users, int64) {
	list := make([]*Users, 0)
	var total int64 = 0

	// 查询
	query := utils.GORM.Debug().Table(u.TableName())

	if len(search) > 0 {
		search = fmt.Sprintf("%%%s%%", search)
		query = query.Where("name like ? or no like ? or email like ?", search, search, search)
	}

	// 总数
	query.Count(&total)

	// 列表
	offset := (page - 1) * pageSize
	query.Limit(pageSize).Offset(offset).Find(&list)

	return list, total
}

// 获取单条数据
func (u *Users) CheckLogin(username string, password string) (*Users, error) {
	//info := make([]*Users, 0)

	// 查询
	query := utils.GORM.Debug().Table(u.TableName())

	query = query.Where("username = ? and password = ?  and status = ?", username, password, 1)

	// 总数
	//query.Count(&total)
	// 列表
	//offset := (page - 1) * pageSize
	err := query.First(&u).Error
	return u, err
}

// 获取单条数据
func (u *Users) First(Preload bool) (*Users, error) {
	//info := make([]*Users, 0)

	// 查询
	query := utils.GORM.Debug().Table(u.TableName())

	//query = query.Where("username = ? and password = ?  and status = 10", username, password)

	// 总数
	//query.Count(&total)
	// 列表
	//offset := (page - 1) * pageSize
	var err error
	if Preload {
		err = query.Preload("Avatar").Preload("Grade").First(&u).Error
	} else {
		err = query.First(&u).Error
	}
	return u, err
}

// 批量更新
func (u *Users) AutoSave(where string, whereColumn interface{}, UpdateData interface{}) *Users {

	fmt.Println("更新用户登录信息")
	// 查询
	query := utils.GORM.Debug().Table(u.TableName())

	// 总数
	query.Model(&u).Where(where, whereColumn, UpdateData).Updates(UpdateData)
	fmt.Println("数据更新完成")
	// 列表
	return u
}

func (u *Users) GetUserConfig() structs.CFConfig {
	list := structs.CFConfig{}
	list.Column = u.Column()
	list.Forms = u.Forms()
	return list
}

func (u *Users) Save() error {
	fmt.Println(u)
	// 更新
	return utils.GORM.Debug().Table(u.TableName()).Omit("Grade").Omit("UploadFile").Save(u).Error
}

// 获取分页列表及总数
func (u *Users) GetListAndTotal(search string, page int, pageSize int) ([]*Users, int64) {
	list := make([]*Users, 0)
	var total int64 = 0

	// 查询
	query := utils.GORM.Debug().Table(u.TableName())

	if len(search) > 0 {
		search = fmt.Sprintf("%%%s%%", search)
		query = query.Where("name like ?", search)
	}

	// 总数
	query.Count(&total)

	// 列表
	offset := (page - 1) * pageSize
	query.Preload("Avatar").Preload("Grade").Limit(pageSize).Offset(offset).Find(&list)

	return list, total
}

func (u *Users) Delete() error {
	return utils.GORM.Debug().Table(u.TableName()).Delete(u).Error
}
